#include "ClientSeekController.h"
#include <fstream>

ClientSeekController::ClientSeekController(Model *m, View *v, NetworkPat* net): Controller(m, v)
{
  _model = (ClientSeekModel*)m;
  _view = (ClientSeekView*)v;
  _net = net;
  mShouldReset = true;
  newGameState = GameState::ClientSeek;
}

ClientSeekController::~ClientSeekController(void)
{
}

void ClientSeekController::HandleMessages(std::list<Message*> *l)
{
  if(l == NULL)
    return;
  if(mShouldReset)
  {
    _net->Reset();
    //read config file and get the address I want
    std::ifstream input;
    input.open("SeekConfig.txt");
    if(input.fail())
    {
      //I don't know
    }
    unsigned short port;
    input >> port;
    input.ignore(100, '\n');
    char ipAddr[MAX_SEEK_LENGTH] = {0};
    input.getline(ipAddr, MAX_SEEK_LENGTH);
    sockaddr_in remote;
    remote.sin_family = AF_INET;
    remote.sin_port = htons(port);
    remote.sin_addr.s_addr = inet_addr(ipAddr);
    _net->AddAddress(remote);
    mShouldReset = false;
  }
  if(_model->IsConnected() == false)
  {
    Message* message = new Message(MessageType::SYSTEM, NetMessage::JOIN);
    _net->Send(message);
  }
  //get messages from the network
  std::list<Message*>* l2 = _net->Recv();

  newGameState = GameState::ClientSeek;
  while(!l2->empty())
  {
    Message* temp = l2->front();
    l2->pop_front();
    if(temp->GetMessageType() == MessageType::SYSTEM)
    {
      switch(temp->GetMessageContent())
      {
        case NetMessage::PLAYER_COUNT_UPDATE:
          _net->SetCount(temp->GetMessageId());
          _model->SetConnect(true);
          break;
        case NetMessage::END:
          mShouldReset = true;
          newGameState = GameState::MainMenu;
          break;
        case NetMessage::ID_ASSIGNMENT:
          _net->SetId(temp->GetMessageId());
          //time to move to playing the game (maybe?)
          if((_net->GetSeed() != 0) && (_net->GetId() != 0))
          {
            mShouldReset = true;
            newGameState = GameState::ClientPlay;
          }
          break;
        case NetMessage::RANDOM_SEED:
          _net->SetSeed(temp->GetMessageId());
          if((_net->GetSeed() != 0) && (_net->GetId() != 0))
          {
            this->mShouldReset = true;
            newGameState = GameState::ClientPlay;
          }
          break;
      }
    }
    delete temp;
  }
}

GameState ClientSeekController::Update(void)
{
  _view->DrawScreen();
  return newGameState;
}

void ClientSeekController::PassMessage(Message* msg)
{
}

void ClientSeekController::ProcessMessages(void)
{
}
